package com.ndp.fb.fbagent.service.impl;

import com.alibaba.dubbo.config.annotation.Service;
import com.alibaba.fastjson.JSON;
import com.ndp.fb.config.ConfigCentre;
import com.ndp.fb.constant.CommonConstants;
import com.ndp.fb.fbagent.service.AdSetFBService;
import com.ndp.fb.model.fbagent.param.APIPriority;
import com.ndp.fb.model.fbagent.param.adset.AdSetParam;
import com.ndp.fb.model.fbagent.result.FacebookResult;
import com.ndp.fb.model.fbagent.result.adset.FbAdSet;
import com.restfb.Parameter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.List;

/**
 * Created by infi on 2015/1/24.
 */
@Service
public class AdSetFBServiceImpl extends AbstractFBagentService implements AdSetFBService {
    private Logger logger = LoggerFactory.getLogger(AdSetFBServiceImpl.class);

    final String AD_SET_FIELDS = "id,name,account_id,campaign_group_id,campaign_status,"
            + "start_time,end_time,created_time,updated_time,daily_budget,lifetime_budget,bid_info,targeting,promoted_object,adlabels,frequency_cap,frequency_cap_reset_period,lifetime_frequency_cap,"
            + "lifetime_imps,optimization_goal,rf_prediction_id,rtb_flag,pacing_type,budget_remaining,bid_amount,billing_event,buying_type";

    private String helperMode = ConfigCentre.getString("helper.mode");


    public void setHelperMode(String helperMode) {
        this.helperMode = helperMode;
    }

    @Override
    public Long getAdSetsSumaryByAccount(String accessToken, Long fbAccountId) {

        AdSetParam adSetParam = new AdSetParam();
//        adSetParam.setSummary("true");
        adSetParam.setFbAccountId(fbAccountId);
        adSetParam.setApiPriorityCode(APIPriority.FetchAdcampaignsCount.getCode());
        List<Parameter> parameterList = adapter(adSetParam);
        String uri = "/act_" + fbAccountId + "/adsets";
        FacebookResult<FbAdSet> result = fetchFacebookResult(uri, accessToken, parameterList, false, 0, CommonConstants.NUM_INT_1, FbAdSet.class);
        return result.getSummary().getTotalCount();
    }


    @Override
    public String updateAdSet(AdSetParam adSetParam) {
        logger.info("updateAdSet>>>" + JSON.toJSONString(adSetParam));
        List<Parameter> parameterList = adapter(adSetParam);
        logger.info("updateAdSet>>>List<Parameter>" + JSON.toJSONString(parameterList));
        String uri = "/" + adSetParam.getAdSetId();
        return makePostRequest(uri, adSetParam.getAccessToken(), parameterList.toArray(new Parameter[]{}));
    }

    @Override
    public void createAdSet(AdSetParam param) {
        logger.debug("createAdCreative>>>"+ JSON.toJSONString(param));
        List<Parameter> parameterList = adapter(param);
        logger.debug("createAdCreative>>>List<Parameter>"+ JSON.toJSONString(parameterList));
        String uri = "/act_" + param.getFbAccountId() + "/adsets";
        makePostRequest(uri, param.getAccessToken(), parameterList.toArray(new Parameter[]{}));
    }
}